#include <bits/stdc++.h>

#define in read()
#define fi first
#define se second
#define pb push_back
#define rep(i, x, y) for(int i = (x); i <= (y); i++)
#define per(i, x, y) for(int i = (x); i >= (y); i--)

using namespace std;

using pii = pair < int , int >;
using vec = vector < int >;
using veg = vector < pii >;
using ll = long long;

int read() {
    int x = 0; bool f = 0; char ch = getchar(); while(!isdigit(ch)) f |= ch == '-',ch = getchar();
    while(isdigit(ch)) x = x * 10 + (ch ^ 48),ch = getchar(); return f ? -x : x;
}

const int N = 2e5 + 10;

int n, a[N], stk[N], top;
int f[N][2], g[N][2], lt[N], rt[N], res[2], cnt[N];
vec pot[N];

struct BIT {
	int tr[N];
	void reset() { memset(tr, 0, sizeof tr); }
	void add(int x, int v) { for(; x <= n; x += x & -x) tr[x] = max(tr[x], v); }
	int query(int x) { int res = 0; for(; x; x -= x & -x) res = max(res, tr[x]); return res; }
} T;
void solve() {
	n = in; rep(i, 1, n) lt[i] = n + 1, cnt[i] = 0, rt[i] = 0, f[i][0] = g[i][0] = f[i][1] = g[i][1] = 0, a[i] = in, pot[i].clear();
	rep(i, 1, n) lt[a[i]] = min(lt[a[i]], i), rt[a[i]] = i, cnt[a[i]]++, pot[a[i]].pb(i);
	T.reset(); res[0] = res[1] = 0;
	rep(i, 1, n) {
		f[i][0] = T.query(a[i]); T.add(a[i], f[i][0] + 1); res[0] = max(res[0], f[i][0]);
	}
	T.reset();
	rep(i, 1, n) {
		f[i][1] = T.query(n - a[i] + 1); T.add(n - a[i] + 1, f[i][1] + 1); res[1] = max(res[1], f[i][1]);
	}
	res[0]++; res[1]++;
	T.reset();
	per(i, n, 1) {
		g[i][1] = T.query(a[i]); T.add(a[i], g[i][1] + 1); 
	}
	T.reset();
	per(i, n, 1) {
		g[i][0] = T.query(n - a[i] + 1); T.add(n - a[i] + 1, g[i][0] + 1);
	}
	int ans = 0; //cerr << res[0] << " " << res[1] << endl;
	rep(i, 1, n) {
		if(!cnt[i]) continue;
		auto v = pot[i];
		rep(j, 0, cnt[i] - 1) {
			rep(k, j, cnt[i] - 1) {
				if(f[v[j]][0] + g[v[k]][0] + k - j + 1 == res[0] && f[v[j]][1] + g[v[k]][1] + k - j + 1 == res[1]) ans = max(ans, k - j + 1);
			}
		}
	}
	printf("%d\n", ans);
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("1.in","r",stdin);
#endif
	int t = in; while(t--) solve();
}
